package net.knightwatch.kwtools;

import java.io.FileInputStream;

import net.knightwatch.kwtools.database.KwToolsDatasource;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity {
	public static final String TAG = "KwToolsActivity";
    /** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main_activity);
	    // TODO Get the excel file to update the forms. 
	    try {
			if(getIntent().getData() != null){
				Log.d(TAG, "Intent Data Detected Proceeding to add forms to");
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage("Importing forms will DELETE ALL Potentials. If you have not exported to engineering please click no and do so before importing the new forms. Customer data will be retained.")
									.setPositiveButton("Yes - Delete It Give me New!", dialogClickListener).setNegativeButton("No - I need this stuff!", dialogClickListener).show();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_activity_menu, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i(TAG, "A button was pressed");
	    switch (item.getItemId()) {
	    case R.id.customers_menu:
	        Intent intent = new Intent(MainActivity.this, CustomerList.class);
	        startActivity(intent);
	        return true;
	    case R.id.potentials_menu:
	    	// TODO Create a Potential List View of all Open Potentials
	    	Intent potentialListIntent = new Intent(MainActivity.this, PotentialListActivity.class);
	    	startActivity(potentialListIntent);
	    	return true;
	    
	    default:
	    	return super.onOptionsItemSelected(item);
	    }
	}
	@SuppressWarnings("resource")
	private FileInputStream getFileStreamFromIntent(Intent intent) {
		// TODO Copy the input file to the temp directory
    	FileInputStream in = null;
    	try{
    		Uri u = intent.getData();
    		Log.d(TAG, "URI Information" + u.getEncodedPath());
    		String scheme = u.getScheme();
    		if(scheme.equals("file")){
    			Log.d(TAG, "Handled as a standard file");
    			Log.d(TAG, "In File Name: " + u.getLastPathSegment());
    			in = new FileInputStream(u.getEncodedPath());
    		} else {
    			Log.d(TAG, "Handled as email attachment");
    			Log.d(TAG, "In File Name: " + getContentName(getContentResolver(), u));
    			in = (FileInputStream) getContentResolver().openInputStream(u);
    		}
    	} catch (Exception e){
    		e.printStackTrace();
    	}        
		return in;
	}
	public static String getContentName(ContentResolver resolver, Uri uri){
	    Cursor cursor = resolver.query(uri, null, null, null, null);
	    cursor.moveToFirst();
	    int nameIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
	    if (nameIndex >= 0) {
	        return cursor.getString(nameIndex);
	    } else {
	        return null;
	    }
	}
	DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	        switch (which){
	        case DialogInterface.BUTTON_POSITIVE:
	            //Yes button clicked
	        	try {
	        		Toast.makeText(MainActivity.this, "Adding new forms please wait.", Toast.LENGTH_LONG).show();
					KwToolsDatasource datasource = new KwToolsDatasource(MainActivity.this);
					datasource.Open();
					datasource.importSheetsFromFile(getFileStreamFromIntent(MainActivity.this.getIntent()));
					datasource.Close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	            break;

	        case DialogInterface.BUTTON_NEGATIVE:
	            //No button clicked
	        	Toast.makeText(MainActivity.this, "New forms will NOT be added. Nothing will be deleted", Toast.LENGTH_SHORT).show();
	            break;
	        }
	    }
	};
}